import React, { useState, useRef } from 'react';
import { Layout, Typography, Button, Card, Row, Col, Avatar, Statistic, message, Progress, Space } from 'antd';
import {
  PictureOutlined,
  UploadOutlined,
  FolderOutlined,
  PoweroffOutlined,
  SettingOutlined,
  CameraOutlined,
  UserOutlined,
  CloudUploadOutlined,
  CloseOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import SettingsModal from '@/components/SettingsModal';
import { useServerConfig } from '@/contexts/ServerConfigContext';
import { uploadApi } from '@/utils/api';
import { getApiKey } from '@/utils/config';

const { Header, Content } = Layout;
const { Title, Text } = Typography;

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [uploadQueue, setUploadQueue] = useState<File[]>([]);
  const [currentFileIndex, setCurrentFileIndex] = useState(0);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [currentFileName, setCurrentFileName] = useState('');
  const [completedCount, setCompletedCount] = useState(0);
  const [uploadResults, setUploadResults] = useState<{ success: number; failed: number }>({ success: 0, failed: 0 });
  const fileInputRef = useRef<HTMLInputElement>(null);
  const uploadingRef = useRef(false);
  const { serverConfig } = useServerConfig();

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const handleSettings = () => {
    setSettingsVisible(true);
  };

  const handleCloseSettings = () => {
    setSettingsVisible(false);
  };

  const handleUploadClick = async () => {
    console.log('=== handleUploadClick 调试信息 ===');
    console.log('当前服务器配置:', serverConfig);
    console.log('baseURL:', `http://${serverConfig.host}:${serverConfig.port}`);
    const apiKey = await getApiKey();
    console.log('获取到的 apiKey:', apiKey);
    console.log('apiKey 是否为空:', !apiKey);

    if (!apiKey) {
      console.log('apiKey 为空，显示错误提示');
      message.error('请先在设置中配置API Key');
      return;
    }

    if (process.env.NODE_ENV === 'development') {
      fileInputRef.current?.click();
    } else {
      const filePaths = await window.electronAPI?.selectFile();
      if (filePaths && filePaths.length > 0) {
        const files: File[] = [];
        for (const filePath of filePaths) {
          const response = await fetch(filePath);
          const blob = await response.blob();
          const fileName = filePath.split('/').pop() || 'image.jpg';
          const file = new File([blob], fileName, { type: blob.type });
          files.push(file);
        }
        await startBatchUpload(files);
      }
    }
  };

  const handleListenModeClick = async () => {
    let config = null;

    try {
      // 优先使用electronAPI读取配置（生产环境）
      if (window.electronAPI && window.electronAPI.getConfig) {
        config = await window.electronAPI.getConfig();
      } else {
        // 开发环境或备用方案：从localStorage读取
        const savedConfig = localStorage.getItem('picshare-config');
        if (savedConfig) {
          config = JSON.parse(savedConfig);
        }
      }

      if (!config) {
        message.error('请先在设置中配置监听目录');
        return;
      }

      if (!config.watchDirectory || !config.watchDirectory.trim()) {
        message.error('请先在设置中配置监听目录');
        return;
      }

      navigate('/listen-mode');
    } catch (error) {
      message.error('读取配置失败，请重试');
    }
  };

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      const fileArray = Array.from(files);
      await startBatchUpload(fileArray);
    }
  };

  const startBatchUpload = async (files: File[]) => {
    const validFiles = files.filter(file => {
      const isImage = file.type.startsWith('image/');
      const rawExtensions = ['arw', 'cr2', 'cr3', 'nef', 'orf', 'rw2', 'pef', 'srw', 'dng', 'raf', '3fr', 'kdc', 'mos', 'mrw', 'nrw', 'gpr'];
      const isRaw = rawExtensions.some(ext => file.name.toLowerCase().endsWith(`.${ext}`));
      return isImage || isRaw;
    });

    if (validFiles.length === 0) {
      message.error('请选择有效的图片文件或RAW照片格式');
      return;
    }

    setUploadQueue(validFiles);
    setCurrentFileIndex(0);
    setCompletedCount(0);
    setUploadResults({ success: 0, failed: 0 });
    setUploading(true);
    uploadingRef.current = true;

    await processUploadQueue(validFiles);
  };

  const cancelUpload = () => {
    setUploading(false);
    uploadingRef.current = false;
    setUploadQueue([]);
    setCurrentFileIndex(0);
    setUploadProgress(0);
    setCurrentFileName('');
    setCompletedCount(0);
    setUploadResults({ success: 0, failed: 0 });
    message.info('上传已取消');
  };

  const processUploadQueue = async (files: File[]) => {
    const apiKey = await getApiKey();
    let newFileCount = 0;
    let duplicateFileCount = 0;
    let failedCount = 0;
    let shouldContinue = true;

    for (let i = 0; i < files.length && shouldContinue; i++) {
      if (!uploadingRef.current) {
        shouldContinue = false;
        break;
      }

      setCurrentFileIndex(i);
      setCurrentFileName(files[i].name);
      setUploadProgress(0);

      try {
        const result = await uploadSingleFile(files[i], apiKey);
        if (result.success) {
          if (result.duplicate) {
            duplicateFileCount++;
          } else {
            newFileCount++;
          }
          setUploadResults({ success: newFileCount + duplicateFileCount, failed: failedCount });
        } else {
          failedCount++;
          setUploadResults({ success: newFileCount + duplicateFileCount, failed: failedCount });
        }
      } catch (error) {
        failedCount++;
        setUploadResults({ success: newFileCount + duplicateFileCount, failed: failedCount });
      }

      setCompletedCount(i + 1);
    }

    setUploading(false);
    uploadingRef.current = false;
    setUploadQueue([]);
    setCurrentFileIndex(0);

    const totalSuccess = newFileCount + duplicateFileCount;
    if (totalSuccess > 0) {
      let successMessage = `上传完成！`;
      if (newFileCount > 0) {
        successMessage += `新文件 ${newFileCount} 个`;
      }
      if (duplicateFileCount > 0) {
        if (newFileCount > 0) successMessage += `，`;
        successMessage += `文件已存在 ${duplicateFileCount} 个`;
      }
      if (failedCount > 0) {
        successMessage += `，失败 ${failedCount} 个`;
      }
      message.success(successMessage);
    } else {
      message.error('所有文件上传失败');
    }
  };

  const uploadSingleFile = async (file: File, apiKey: string): Promise<{ success: boolean; duplicate?: boolean }> => {
    try {
      console.log('使用 uploadApi 上传文件，服务器配置:', serverConfig);

      const result = await uploadApi.upload(file, apiKey, serverConfig, (progress) => {
        setUploadProgress(progress);
      });

      console.log('上传结果:', result);

      // 返回详细的上传结果
      return {
        success: result.success || result.duplicate,
        duplicate: result.duplicate
      };
    } catch (error) {
      console.error('上传失败:', error);
      return { success: false };
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept="image/*,.arw,.cr2,.cr3,.nef,.orf,.rw2,.pef,.srw,.dng,.raf,.3fr,.kdc,.mos,.mrw,.nrw,.gpr"
        multiple
        onChange={handleFileChange}
      />
      <Header style={{
        background: 'white',
        padding: '0 24px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <PictureOutlined style={{ fontSize: '24px', color: '#667eea' }} />
          <Title level={3} style={{ margin: 0 }}>PicShare</Title>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <Avatar size="large" style={{ backgroundColor: '#667eea' }}>
            <UserOutlined />
          </Avatar>
          <Button
            key="settings"
            type="text"
            icon={<SettingOutlined style={{ fontSize: '18px' }} />}
            title="设置"
            onClick={handleSettings}
            style={{ border: 'none', boxShadow: 'none' }}
          />
          <Button
            type="text"
            icon={<PoweroffOutlined style={{ fontSize: '18px' }} />}
            onClick={handleLogout}
            title="退出"
            style={{ color: '#ff4d4f' }}
          />
        </div>
      </Header>

      <Content style={{ padding: '24px' }}>
        <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
          <div style={{
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            borderRadius: '12px',
            padding: '32px',
            marginBottom: '32px',
            color: 'white'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '16px' }}>
              <CameraOutlined style={{ fontSize: '48px' }} />
              <div>
                <Title level={1} style={{ margin: 0, color: 'white' }}>
                  欢迎您，摄影师！
                </Title>
                <Text style={{ fontSize: '18px', color: 'rgba(255,255,255,0.9)' }}>
                  {user?.nickname}，准备好分享您的精彩作品了吗？
                </Text>
              </div>
            </div>
          </div>

          <Row gutter={[24, 24]} style={{ marginBottom: '32px' }}>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="已上传图片"
                  value={0}
                  prefix={<PictureOutlined />}
                  valueStyle={{ color: '#667eea' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="存储空间"
                  value={0}
                  suffix="MB"
                  prefix={<CloudUploadOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="今日上传"
                  value={0}
                  prefix={<UploadOutlined />}
                  valueStyle={{ color: '#fa8c16' }}
                />
              </Card>
            </Col>
          </Row>

          <div style={{ marginBottom: '24px' }}>
            <Title level={3}>快速操作</Title>
          </div>

          <Row gutter={[24, 24]}>
            <Col xs={24} sm={12} lg={8}>
              <Card
                hoverable={!uploading}
                style={{ height: '200px' }}
                styles={{
                  body: {
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: '100%',
                    padding: '24px'
                  }
                }}
                onClick={!uploading ? handleUploadClick : undefined}
              >
                {uploading ? (
                  <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '12px' }}>
                    <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <Title level={5} style={{ margin: 0, fontSize: '14px' }}>
                          批量上传中...
                        </Title>
                        <Text type="secondary" style={{ fontSize: '11px' }}>
                          {currentFileName}
                        </Text>
                      </div>
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px', textAlign: 'center', fontWeight: 'bold' }}>
                      已完成 {completedCount}/{uploadQueue.length}
                    </Text>
                    <Progress
                      percent={uploadProgress}
                      status={uploadProgress === 100 ? 'success' : 'active'}
                      strokeColor={{
                        '0%': '#667eea',
                        '100%': '#764ba2',
                      }}
                      size="small"
                    />
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text type="secondary" style={{ fontSize: '11px' }}>
                        {uploadProgress}%
                      </Text>
                      <Text type="success" style={{ fontSize: '11px' }}>
                        成功 {uploadResults.success}
                      </Text>
                      <Text type="danger" style={{ fontSize: '11px' }}>
                        失败 {uploadResults.failed}
                      </Text>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <Button
                        size="small"
                        type="primary"
                        danger
                        icon={<CloseOutlined />}
                        onClick={cancelUpload}
                      >
                        取消上传
                      </Button>
                    </div>
                  </div>
                ) : (
                  <>
                    <UploadOutlined style={{ fontSize: '48px', color: '#667eea', marginBottom: '16px' }} />
                    <Title level={4} style={{ margin: 0 }}>上传图片</Title>
                    <Text type="secondary">支持批量选择图片和RAW格式</Text>
                  </>
                )}
              </Card>
            </Col>

            <Col xs={24} sm={12} lg={8}>
              <Card
                hoverable
                style={{ height: '200px' }}
                bodyStyle={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: '100%'
                }}
              >
                <FolderOutlined style={{ fontSize: '48px', color: '#52c41a', marginBottom: '16px' }} />
                <Title level={4} style={{ margin: 0 }}>我的相册</Title>
                <Text type="secondary">浏览所有上传的图片</Text>
              </Card>
            </Col>

            <Col xs={24} sm={12} lg={8}>
              <Card
                hoverable
                style={{ height: '200px' }}
                styles={{
                  body: {
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: '100%'
                  }
                }}
                onClick={handleListenModeClick}
              >
                <EyeOutlined style={{ fontSize: '48px', color: '#52c41a', marginBottom: '16px' }} />
                <Title level={4} style={{ margin: 0 }}>监听模式</Title>
                <Text type="secondary">自动监听目录并上传新照片</Text>
              </Card>
            </Col>
          </Row>
        </div>
      </Content>

      <SettingsModal
        visible={settingsVisible}
        onClose={handleCloseSettings}
      />
    </Layout>
  );
};

export default Dashboard;